//
//  OtherProfileViewController.swift
//  iModern
//
//  Created by Ralf on 5/14/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class OtherProfileViewController: TableViewController
{
    var activites      = NSMutableArray()
    var max:      Int  = 0
    var offset:   Int  = 0
    var end            = false
    var appDelegate    = UIApplication.sharedApplication().delegate as! AppDelegate
    var articleManager = ArticleManager()
    var contact:  [String:AnyObject]!
    var userName: String!
    var scrollView = UIScrollView()
    

    let screen      = UIScreen.mainScreen().bounds
    let __background_image_view_tag = 10
    let __avatar_image_view_tag     = 11
    let __alias_label_tag     = 20
    let __about_me_label_tag  = 21
    let __signature_label_tag = 22
    let __follow_label_tag    = 23
    let __name_label_tag      = 44
    let __follow_button_tag   = 30
    let view1 = UIView()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "ProfileViewOtherAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AVATAR")
//        self.tableView.registerNib(UINib(nibName: "ProfileViewOtherSummaryCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "SUMMARY")
//        self.tableView.registerNib(UINib(nibName: "ProfileViewArticleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ARTICLE")
//        self.tableView.registerNib(UINib(nibName: "ProfileViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
//        self.tableView.registerNib(UINib(nibName: "ProfileViewTaskCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Task")

        self.tableView.registerNib(UINib(nibName: "OtherShopCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "SHOP")
        self.tableView.registerNib(UINib(nibName: "OtherShopNoticeCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "NOTICE")
        
        
        initView(self.contact)
//        self.loadData()
        initBackButton()
        self.navigationItem.title = nil
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return activites.count + 1
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell: UITableViewCell

        switch indexPath.row
        {
//        case 0:
//            var c
//            = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! ProfileViewOtherAvatarCell
//            //            if (appDelegate.isLogged())
//            //            {
//            c.setData(self.contact)
//            //            }
//            cell = c
        case 0:
            let c
            = tableView.dequeueReusableCellWithIdentifier("NOTICE", forIndexPath: indexPath) as! OtherShopNoticeCell
            c.setData(self.contact)
            c.selectionStyle = UITableViewCellSelectionStyle.None
            cell = c
        default:
            let article = activites[indexPath.row - 1]["article"] as! NSMutableDictionary
            let type    = article["type"] as? String
            if (type == "Article")
            {
                let c
                = tableView.dequeueReusableCellWithIdentifier("ARTICLE", forIndexPath: indexPath) as! ProfileViewArticleCell
                c.setData(activites[indexPath.row - 1] as! NSMutableDictionary)
                cell = c
            }
            else if (type == "Advertising")
            {
                //                cell = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! UITableViewCell
//                var c
//                = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! ProfileViewAdvertisingCell
                let c
                = tableView.dequeueReusableCellWithIdentifier("SHOP", forIndexPath: indexPath) as! OtherShopCell
                c.setData(activites[indexPath.row - 1] as! NSMutableDictionary)
                cell = c
            }
            else
            {
                let c
                = tableView.dequeueReusableCellWithIdentifier("Task", forIndexPath: indexPath) as! ProfileViewTaskCell
                c.setData(activites[indexPath.row - 1] as! NSMutableDictionary)
                cell = c
            }
        }

        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */

    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */
    func initView(data: NSDictionary)
    {
        initBackgroundImageView(data)
        initAvatarImageView(data)
        initAliasLabel(data)
        initFollowButton(data)
        initSignatureLabel(data)
        initNameLabel(data)
        

        let screen = UIScreen.mainScreen().bounds
        
        view1.frame = CGRectMake(0, 10, 300, 300)
        view1.backgroundColor = UIColor.groupTableViewBackgroundColor()
        self.tableView!.tableHeaderView = view1
        
        let sframe = CGRect(x: 0, y: 250, width: screen.size.width, height: 40)
        scrollView = UIScrollView(frame: sframe)
        scrollView.indicatorStyle = UIScrollViewIndicatorStyle.Black
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.backgroundColor = UIColor.whiteColor()
        view1.addSubview(scrollView)
        
        var a = ["服装", "珠宝", "鞋子", "箱包", "绘画", "皮艺", "纸艺", "陶艺", "女红", "纹身", "玩具", "乐器", "茶艺", "陶艺", "文玩", "绘画", "家具", "装修", "园艺", "女红", "修理", "美食", "布艺", "美妆", "健康", "茶艺", "酒水", "纹身", "电子科技"]
        var n = Int()
        var index: Int
        for index = 1; index < 10; ++index
        {
            n = 10 + 50 * index
            let tapSingle=UITapGestureRecognizer(target:self,action:"tapSingleDid:")
            tapSingle.numberOfTapsRequired=1
            tapSingle.numberOfTouchesRequired=1
            
            var label = UILabel()
            let frame = CGRect(x:n - 50, y: 5, width: 40, height: 30)
            label = UILabel(frame: frame)
            label.font = UIFont.systemFontOfSize(12)
            label.text = a[index - 1]
            label.tag = index
            label.textColor = UIColor.whiteColor()
            label.backgroundColor = UIColor.clearColor()
            if index == 1
            {
                label.backgroundColor = Theme.score_color
            }
            else
            {
                label.backgroundColor = Theme.theme_color
            }
            label.textAlignment = NSTextAlignment.Center
            label.layer.masksToBounds = true
            label.layer.cornerRadius = 4
            label.userInteractionEnabled = true
            label.addGestureRecognizer(tapSingle)
            scrollView.addSubview(label)
            scrollView.contentSize = CGSizeMake(CGFloat(n), CGFloat(0))
        }
    }

    func loadData()
    {
        if (end)
        {
            return; }

        var rs = appDelegate.contactManager.queryByUserName(userName)

        if self.verifyResutSet(rs)
        {
            if (!rs.isEmpty())
            {
                self.contact = rs.toDictionary() as! [String:AnyObject]
            }
            else
            {
                self.alertWarningMessage("用户不存在")
                self.navigationController?.popViewControllerAnimated(true)
                return
            }
        }

        rs = articleManager.queryByUserName(userName, max: max, offset: offset)

        if (self.verifyResutSet(rs))
        {
            if (rs.isEmpty())
            {
                end = true
            }
            else
            {
                activites.addObjectsFromArray(rs.toMutableArray() as [AnyObject])
                offset = activites.count
            }
        }

        self.navigationItem.title = self.contact["alias"] as? String

        self.tableView.reloadData()
    }

    @IBAction override func reloadData(sender: AnyObject?)
    {
        offset = 0
        end = false
        activites.removeAllObjects()
        self.loadData()
        super.reloadData(sender)
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        //let screen = UIScreen.mainScreen().bounds
        switch indexPath.row
        {
//        case 0:
//            return 240
//            //        case 1:
//            //            return 40
        case 0:
            return 40
        default:
            return 110//screen.size.width + 100
        }
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if indexPath.row > 0
        {
            let activity = activites[indexPath.row - 1] as! NSMutableDictionary
            let article  = activity["article"] as! [String:AnyObject]
            let type     = article["type"] as! String

            if type == "Article"
            {
                let controller = ArticlePageViewController()
                controller.activity = activity
                self.pushViewController(controller)

            }
            else if type == "Advertising"
            {
                let controller = AdvertisingPageViewController()
                controller.activity = activity
                self.pushViewController(controller)
            }
        }
    }

    func loadDataByUserName(userName: String)
    {
        self.userName = userName
        loadData()
    }

    @IBAction func loadMessageViewController(sender: UIButton)
    {
        if (appDelegate.isLogged())
        {
            let controller = ChatViewController()
            controller.contact = self.contact
            self.pushViewController(controller)
        }
        else
        {
            self.login()
        }
    }
    
    func tapSingleDid(send: UITapGestureRecognizer)
    {
        //        println(send.view!.tag)
        var index: Int
        for index = 1; index < 10; ++index
        {
            let label = self.view.viewWithTag(index) as? UILabel
            label?.backgroundColor = Theme.theme_color
            label?.textColor = UIColor.whiteColor()
        }
        let label = self.view.viewWithTag(send.view!.tag) as? UILabel
        label?.backgroundColor = Theme.score_color
        label?.textColor = UIColor.whiteColor()
        
        switch send.view!.tag
        {
        case 1:
            print("fuzhuang")
            
            reloadData(send)
        case 2:
            print("zhubao")
            reloadData(send)
        case 3:
            print("xiezi")
        case 4:
            print("xiangbao")
        case 5:
            print("huihua")
        case 6:
            print("piyi")
        case 7:
            print("ziyi")
        case 8:
            print("taoyi")
        case 9:
            print("nvhong")
        default:
            break
        }
        
    }
    
    func initBackgroundImageView(data: NSDictionary)
    {
        var imageView = self.view.viewWithTag(__background_image_view_tag) as? UIImageView

        let backgroundURL = data["backgroundURL"] as? String
        if (backgroundURL != nil)
        {
            imageView = self.view.viewWithTag(__background_image_view_tag) as? UIImageView
            imageView!.load(appDelegate.parameterManager.server + "/" + backgroundURL!, placeholder: nil)
        }
        if (imageView == nil)
        {
            let frame = CGRect(x: 0, y: 0, width: screen.size.width, height: 240)
            imageView = UIImageView(frame: frame)
            imageView!.tag = __background_image_view_tag
            imageView!.image = UIImage(named: "Avatar-Backgound.png")
            view1.addSubview(imageView!)
        }
    }
    
    func initAvatarImageView(data: NSDictionary)
    {
        
        var imageView = self.view.viewWithTag(__avatar_image_view_tag) as? UIImageView
        let imageURL = data["shopLogoURL"] as? String
        if (imageView == nil)
        {
            let x     = (screen.size.width - 100) / 2
            let frame = CGRect(x: x, y: 30, width: 100, height: 100)
            imageView = UIImageView(frame: frame)
            imageView!.tag = __avatar_image_view_tag
            imageView!.layer.cornerRadius = 50
            imageView!.layer.masksToBounds = true
            imageView!.layer.borderColor = UIColor.blackColor().CGColor
            imageView!.layer.borderWidth = 1
            if imageURL != nil
            {
                let url       = appDelegate.parameterManager.server + "/" + imageURL!
                imageView!.load(url, placeholder: nil)
            }
            else
            {
                imageView!.image = UIImage(named: "Avatar-Default.png")
            }
            view1.addSubview(imageView!)
        }
    }
    
    func initAliasLabel(data: NSDictionary)
    {
        var label = self.view.viewWithTag(__alias_label_tag) as? UILabel
        let name = data["shopName"] as? String
        if (label == nil)
        {
            let frame = CGRect(x: 0, y: 130, width: screen.width, height: 40)
            label = UILabel(frame: frame)
            label!.textAlignment = .Center
            label!.tag = __alias_label_tag
            label!.font = UIFont.systemFontOfSize(20)
            label!.textColor = UIColor.whiteColor()
            label!.shadowColor = UIColor.darkGrayColor()
            label!.shadowOffset = CGSizeMake(1, 1)
            if name != nil
            {
                label?.text = name
            }
            view1.addSubview(label!)
        }
    }
    
    func initFollowButton(data: NSDictionary)
    {
        
        var button = self.view.viewWithTag(__follow_button_tag) as? UIButton
        if (button == nil)
        {
            let x     = (screen.size.width - 200) / 2
            let frame = CGRect(x: x + 180, y: 160, width: 30, height: 30)
            button = UIButton(frame: frame)
            button!.contentMode = .Left
            button!.titleLabel?.font = UIFont.systemFontOfSize(12)
            button!.titleLabel!.shadowColor = UIColor.darkGrayColor()
            button!.titleLabel!.shadowOffset = CGSizeMake(1, 1)
            button!.tag = __follow_button_tag
            button!.imageView?.contentMode = .ScaleAspectFit
            button!.setImage(UIImage(named: "Message-60.png"), forState: .Normal)
            view1.addSubview(button!)
        }
        button!.addTarget(self, action: Selector("SendMessage"), forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    func initNameLabel(data: NSDictionary)
    {
        var labelName = self.view.viewWithTag(__name_label_tag) as? UILabel
        let fullName  = data["fullName"] as? String
        let city      = data["city"] as? String
        if (labelName == nil)
        {
            let x     = (screen.size.width - 200) / 2
            let frame = CGRect(x: x, y: 160, width: 180, height: 30)
            labelName = UILabel(frame: frame)
            labelName!.textAlignment = .Center
            labelName!.tag = __name_label_tag
            labelName!.font = UIFont.systemFontOfSize(12)
            labelName!.textColor = UIColor.whiteColor()
            labelName!.shadowColor = UIColor.darkGrayColor()
            labelName!.shadowOffset = CGSizeMake(1, 1)
            if fullName == nil || city == nil
            {
                labelName!.text = "匠人名称       哪里人"
            }
            else
            {
                labelName!.text = fullName! + "       " + city!
            }
            view1.addSubview(labelName!)
        }
 
    }
    
    func initSignatureLabel(data: NSDictionary)
    {
        var label = self.view.viewWithTag(__signature_label_tag) as? UILabel
        let address = data["address"] as? String
        if (label == nil)
        {
            let frame = CGRect(x: 0, y: 210, width: screen.width, height: 20)
            label = UILabel(frame: frame)
            label!.textAlignment = .Center
            label!.tag = __signature_label_tag
            label!.font = UIFont.systemFontOfSize(12)
            label!.textColor = UIColor.whiteColor()
            label!.shadowColor = UIColor.darkGrayColor()
            label!.shadowOffset = CGSizeMake(1, 1)
            if address == nil
            {
                label!.text = "匠铺地址：北京市朝阳区默默大厦120层1203"
            }
            else
            {
                label!.text = address

            }
            view1.addSubview(label!)
        }
    }
    
    func SendMessage()
    {
        if appDelegate.isLogged()
        {
            let controller = ChatViewController()
            controller.contact = self.contact as [String:AnyObject]
            self.pushViewController(controller)
        }
        else
        {
            self.login()
        }
    }
}
